import {useUserInfoStore} from "../../stores/modules/userInfo";
import {ref} from "vue";
import {onLoad} from "@dcloudio/uni-app";
import {conUtils} from "../../utils/conUtils";
import {BaseURL} from "../../utils/lshttp";
import {getLoginCode, getNewsLoginCode} from "../../services/login";
import {
    bindTelAPI,
    getImageCodeAPI,
    getUserInfoAPI,
    giveMemberAPI,
    updateNicknameAndAvatarAPI
} from "../../services/me";
import {requestAndroidPermission} from "../../js_sdk/wa-permission/permission";

export const UseSettingInfo = () => {

    // 用户信息
    const userInfoStore = useUserInfoStore()
    // 默认头像地址
    const myAvatarUrlNormal = ref("https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0")
    // 我的头像地址
    const myAvatarUrl = ref('')
    // 我的验证码数字
    const codeText = ref('获取验证码')
    // 验证码
    const myCode = ref()
    // 圖像验证码
    const verify = ref()
    // 用戶昵称
    const nickname = ref()
    // 用户电话
    const userPhone = ref('')
    // 美团电话
    const mtPhone = ref('')
    // 验证码
    const userCode = ref('')
    // 验证码圖像
    const verifyCodeImg = ref('')
    // 是否显示图像验证码
    const show = ref(false)
    // 用户信息
    const user = ref()

    onLoad(() => {
        // uni.showToast({title: "请先绑定手机号和用户信息", icon: "none", duration: 3000})
        myAvatarUrlNormal.value = "https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0"
        user.value = userInfoStore.userInfo
        myAvatarUrlNormal.value = user.value.avatar
        mtPhone.value = userInfoStore.userInfo.mt_phone
        if (user.value.avatar !== myAvatarUrlNormal) {
            myAvatarUrl.value = user.value.avatar
        }
        if (user.value.nickname !== '微信用户') {
            nickname.value = user.value.nickname
        }
    })
    // 修改头像
    const onChooseAvatar = (e) => {
        const avatarUrl = e.detail.avatarUrl
        conUtils("avatarUrl", avatarUrl)
        uni.uploadFile({
            url: BaseURL + '/api/user/uploadAvatar',
            method: 'POST',
            filePath: avatarUrl,
            name: 'file',
            success(res1) {
                conUtils("res1", res1)
                uni.hideLoading()
                let data = JSON.parse(res1.data)
                if (data.status !== 1) {
                    uni.showToast({
                        title: res1.msg,
                        icon: 'none'
                    })
                    return
                }
                myAvatarUrl.value = data.result.show_path
            }, fail(error) {
                conUtils("error", error)
            }
        })
    }
    // 上传头像
    const uploadMyImg = () => {
        uni.chooseImage({
            count: 1,
            // 默认9
            sizeType: ['original', 'compressed'],
            // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album'],
            // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                const tempFilePaths = res.tempFilePaths;
                uni.showLoading({
                    title: '上传中'
                })
                uni.uploadFile({
                    url: BaseURL + '/api/user/uploadAvatar',
                    method: 'POST',
                    filePath: tempFilePaths[0],
                    name: 'file',
                    header: {
                        authorization: uni.getStorageSync('token')
                    },
                    success(res) {
                        uni.hideLoading()
                        let data = JSON.parse(res.data)
                        myAvatarUrl.value = data.result.show_path
                    }
                })
            }
        });
    }
    // 获取输入内容
    const getInputValue = (e) => {
        nickname.value = e.detail.value
    }
    // 获取验证码
    const getCode = async () => {
        if (userPhone.value.length !== 11) {
            await uni.showToast({title: "请输入手机号", icon: "none"})
            return
        }
        if (!verify.value) {
            show.value = true
            await getVerify()
            return
        }
        if (myCode.value.canGetCode) {
            const res = await getNewsLoginCode(userPhone.value, verify.value)
            if(res.result.isSuccess){
                myCode.value.start()
            }else{
                await uni.showToast({title: res.msg, icon: "none"})
                verify.value = ""
            }
        } else {
            this.$u.toast('倒计时结束后再发送')
        }
    }
    // 验证码改变
    const codeChange = (text) => {
        codeText.value = text
    }
    // 确认获取验证码
    const yesGetCode = () => {
        show.value = false
        getCode()
    }
    // 去美团帮助
    const toMTHelp = () => {
        uni.navigateTo({
            url: "/pages/index/mt_phone_help"
        })
    }
    // 获取验证码图片
    const getVerify = async () => {
        const res = await getImageCodeAPI({
            tel: userPhone.value,
            type: 'base64'
        })
        verifyCodeImg.value = res.result.base64
    }
    // 确定修改昵称
    const handleChangeNickname = async () => {
        conUtils("myAvatarUrl", myAvatarUrl.value)
        conUtils("nickname", nickname.value)
        conUtils("userPhone", userPhone.value)
        if (!myAvatarUrl.value) {
            await uni.showToast({title: "请设置头像", icon: "none"})
            return
        }
        if (!nickname.value) {
            await uni.showToast({title: "请输入昵称", icon: "none"})
            return
        }
        if (userPhone.value.length !== 11) {
            await uni.showToast({title: "请输入手机号", icon: "none"})
            return
        }
        if (mtPhone.value.length !== 11) {
            await uni.showToast({title: "请输入美团绑定对的手机号", icon: "none"})
            return
        }
        await bindTelAPI({tel: userPhone.value, mt_phone: mtPhone.value, code: userCode.value})
        // await bindTelAPI({tel: userPhone.value, code: userCode.value})
        await updateNicknameAndAvatarAPI({avatar: myAvatarUrl.value, nickname: nickname.value})
        await uni.showToast({title: "保存成功", icon: "none", duration: 2000})
        const resUser = await getUserInfoAPI()
        userInfoStore.setUserInfo(resUser.result)
        const res = await giveMemberAPI()
        await uni.showToast({
            title: res.msg,
            icon: 'none'
        })
        setTimeout(() => {
            uni.navigateBack()
        }, 2000)
    }
    const isYJJJ = ref(false)
    // 获取权限
    const getPermission = async () => {
        let platform = uni.getSystemInfoSync().platform
        if (platform === 'ios') {
            uploadMyImg()
            return
        }

        const photo = uni.getStorageSync("photo")
        if (photo) {
            uploadMyImg()
            return
        }
        uni.showModal({
            title: '提示',
            content: "修改头像需要获取您设备上的相册权限，是否同意授权？",
            confirmText: '同意授权',
            success: async function (res) {
                if (res.confirm) {
                    const result = await requestAndroidPermission("android.permission.READ_EXTERNAL_STORAGE")
                    if (result === 1) {
                        uni.setStorageSync("photo", true)
                        uploadMyImg()
                    } else if (result === 0) {
                        uni.setStorageSync('photo', false)
                        // await uni.showToast({
                        //   title: '你已拒绝权限,请开启权限！',
                        //   icon: 'none',
                        //   duration: 3000
                        // })
                    } else {
                        uni.setStorageSync('photo', false)
                        isYJJJ.value = true
                        // await uni.showToast({
                        //   title: '你已拒绝权限申请,请手动开启权限',
                        //   icon: 'none',
                        //   duration: 3000
                        // })
                        // uni.showModal({
                        //   title: '提示',
                        //   content: "你已拒绝权限申请,是否手动开启权限？",
                        //   confirmText: '打开设置',
                        //   success: async function (res) {
                        //     if (res.confirm) {
                        //       // 打开权限设置界面
                        //       gotoAppPermissionSetting();
                        //     }
                        //   }
                        // })
                    }
                }
            }
        })
    }

    return{
        userInfoStore,
        myAvatarUrlNormal,
        myAvatarUrl,
        codeText,
        myCode,
        verify,
        nickname,
        userPhone,
        mtPhone,
        userCode,
        verifyCodeImg,
        show,user,
        onChooseAvatar,
        uploadMyImg,
        getInputValue,
        getCode,
        codeChange,
        yesGetCode,
        toMTHelp,
        handleChangeNickname,
        getPermission,
    }
}